package com.bw.finance.alipay;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.finance.conf.AlipayConfig;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.locana.EbankAccountLog;
import com.bw.finance.eneity.user.EbankBorrower;
import com.bw.finance.eneity.user.EbankInvestor;
import com.bw.finance.service.IEbankAccountLogService;
import com.bw.finance.service.IEbankBorrowerService;
import com.bw.finance.service.IEbankInvestorService;
import com.bw.finance.utils.IdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-06
 */
@RestController
@RequestMapping("alipay")
public class AlipayController {
    @Autowired
    private IEbankAccountLogService ebankAccountLogService;

    @Autowired
    private IEbankBorrowerService borrowerService;

    @Autowired
    private IEbankInvestorService investorService;

    private static final Logger log= LoggerFactory.getLogger(AlipayController.class);

    /*@Autowired
    private IdWorker idWorker;*/

    /**
     * 订单支付调用接口，返回页面String形式
     * @param ebankAccountLog
     * @return
     */
    @PostMapping("pay")
    public ResponseResult pay(@RequestBody EbankAccountLog ebankAccountLog){//对象中有用户id
        log.info("充值记录开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //long code = idWorker.nextId();
            IdWorker idWorker = new IdWorker(1, 1, 1);
            String code= String.valueOf(idWorker.nextId());

            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            alipayRequest.setBizContent("{\"out_trade_no\":\""+code+"\","
                    + "\"total_amount\":\""+ebankAccountLog.getAmount() +"\","
                    + "\"subject\":\""+"1111" +"\","
                    + "\"body\":\""+ "2222" +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String res=alipayClient.pageExecute(alipayRequest).getBody();

            EbankAccountLog ebankAccountLog01 = new EbankAccountLog();//new 一个充值对象
            ebankAccountLog01.setUserId(ebankAccountLog.getUserId());//用户id
            ebankAccountLog01.setUserType(ebankAccountLog.getUserType());//用户的类型
            ebankAccountLog01.setAmount(ebankAccountLog.getAmount());//金额
            ebankAccountLog01.setActionTime(new Date());//操作时间
            ebankAccountLog01.setDingdan_code(code);
            ebankAccountLogService.saveOrUpdate(ebankAccountLog01);//添加历史记录

            result.setMessage("充值记录成功");
            result.setResult(res);
        }catch (Exception e){
            log.error("充值记录失败"+e.toString());
            result.setSuccess(false);
            result.setMessage("充值记录失败"+e.toString());
        }
        log.info("充值记录结束");
        return result;
    }

    /**
     * 订单支付通知
     * @param request
     * @return
     */
    @GetMapping("checksign/{id}/{type}")
    public ResponseResult checksign(HttpServletRequest request,@PathVariable Long id,@PathVariable Integer type){
        log.info("充值记录通知开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //获取地址参数信息
            String ordercode = request.getParameter("out_trade_no");
            String amount=request.getParameter("total_amount");
            String trade_no=request.getParameter("trade_no");//支付宝交易号
            //格式转换
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified==false){//支付宝当时验签一直是失败的非个人问题故==false
                log.info("状态修改，日志添加开始");
                //查到发起支付的记录进行信息补全
                QueryWrapper<EbankAccountLog> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(EbankAccountLog::getDingdan_code,ordercode);
                EbankAccountLog ebankAccountLog = ebankAccountLogService.getOne(queryWrapper);
                //交易流水号
                ebankAccountLog.setTradeNo(trade_no);
                //设置到账时间
                ebankAccountLog.setArriveTime(new Date());
//                //充值多少钱
//                BigDecimal a= new BigDecimal(amount);//String转为BigDecimal转为类型
//                ebankAccountLog.setAmount(a);

                //(0:支付宝 1:微信 2:招商网银)
                ebankAccountLog.setChannelType(0);
                //充值类型是充值（0）还是提现（1）
                ebankAccountLog.setType(0);

                ebankAccountLogService.saveOrUpdate(ebankAccountLog);//添加充值日志
                if(type==0){
                    EbankBorrower borrower = borrowerService.getById(id);
                    BigDecimal am = new BigDecimal(amount);
                    borrower.setBalance(borrower.getBalance().add(am));
                    borrowerService.saveOrUpdate(borrower);
                }
                if(type==1){
                    EbankInvestor investor = investorService.getById(id);
                    BigDecimal am = new BigDecimal(amount);
                    investor.setBalance(investor.getBalance().add(am));
                    investorService.saveOrUpdate(investor);
                }
                result.setResult(ebankAccountLog);
                result.setMessage("充值记录成功");
                log.info("状态修改，日志添加结束");
            }else{
                result.setSuccess(false);
                result.setMessage("验签失败");
            }
        }catch (Exception e){
            log.error("充值记录通知异常"+e.toString());
            result.setSuccess(false);
            result.setMessage("充值记录失败");
        }
        log.info("充值记录通知结束");
        return result;
    }
}
